package com.ghostbusters.danceathon.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

public class RemoteRequestUtil {

	private static Logger logger = Logger.getLogger(RemoteRequestUtil.class);

	public static String get(String endpoint, NameValuePair[] parameters,
			boolean async, boolean encode) throws Exception {
		String requestString = "";
		String name;
		String value;
		for (NameValuePair parameter : parameters) {
			if (!StringUtil.isNullOrEmpty(requestString)) {
				requestString += "&";
			}
			try {
				name = parameter.getName();
				value = parameter.getValue();
				if (encode) {
					requestString += name
							+ "="
							+ (StringUtil.isNullOrEmpty(value) ? ""
									: URLEncoder.encode(parameter.getValue(),
											"UTF-8"));
				} else {
					requestString += name
							+ "="
							+ (StringUtil.isNullOrEmpty(value) ? "" : parameter
									.getValue());
				}
			} catch (UnsupportedEncodingException e) {
				throw new Exception(e);
			}
			// requestString+= parameter.getName() + "=" + parameter.getValue();
		}

		logger.debug("URI: " + endpoint + requestString);

		return get(endpoint, requestString, async);
	}

	public static String get(String endpoint, String requestParameters,
			boolean async) throws Exception {
		return get(endpoint, requestParameters, null, null, async);
	}

	/**
	 * Sends an HTTP GET request to a url
	 * 
	 * @param endpoint
	 *            - The URL of the server. (Example:
	 *            " http://www.yahoo.com/search")
	 * @param requestParameters
	 *            - all the request parameters (Example:
	 *            "param1=val1&param2=val2"). Note: This method will add the
	 *            question mark (?) to the request - DO NOT add it yourself
	 * @param async
	 *            if true, the request will return instantly
	 * @return - The response from the end point
	 * @throws FatalException
	 */
	@SuppressWarnings("deprecation")
	public static String get(String endpoint, String requestParameters,
			String username, String password, boolean async) throws Exception {
		// Send a GET request to the servlet
		HttpClient client = new HttpClient();

		GetMethod get = new GetMethod(endpoint);

		get.setQueryString(requestParameters);
		if (username != null) {
			client.getState().setCredentials(AuthScope.ANY,
					new UsernamePasswordCredentials(username, password));
			get.setDoAuthentication(true);
		}

		if (async) {
			client.setConnectionTimeout(1);
			client.setTimeout(1);
		}

		try {
			// execute
			client.executeMethod(get);

			// print the status and response
			InputStream responseStream = get.getResponseBodyAsStream();
			return StringUtil.convertStreamToString(responseStream);

		} catch (HttpException e) {
			throw new Exception(e);
		} catch (IOException e) {
			throw new Exception(e);
		} finally {
			// release any connection resources used by the method
			get.releaseConnection();
		}
	}
}
